package com.bys.ots.config.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class WxTokenUpdate
{
    private final Logger logger = LoggerFactory.getLogger(WxTokenUpdate.class);

    @Autowired
    WxConfig wxConfig;

    private boolean isSuccess = true;

    public static String accessToken = "";





    public void updateToken()
    {
        isSuccess = false;
        int i = 0;
        updateTokenDetail();
        i++;

        while (i < 3)
        {
            if (!isSuccess)
            {
                updateTokenDetail();
            }
            i++;
        }
    }

    public void updateTokenDetail()
    {

        JSONObject re = null;
        String url = wxConfig.getWxGetTokenUrl();
        String appsecret = wxConfig.getSecret();
        String appid = wxConfig.getAppId();
        url = url.replace("SECRET", appsecret);
        url = url.replace("APPID", appid);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = null;
        CloseableHttpResponse response = null;
        try
        {
            URIBuilder uriBuilder = new URIBuilder(url);
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            httpGet.addHeader("Content-Type", "text/xml; charset=utf-8");
            httpGet.addHeader("Accept-Charset", "utf-8");
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "UTF-8");
            if (StringUtils.isNotEmpty(result))
            {
                re = JSON.parseObject(result);
            }
            accessToken = re.getString("access_token");
            isSuccess = true;
            if (StringUtils.isEmpty(accessToken))
            {
                isSuccess = false;
                logger.error("更新微信token接口异常," + re.getString("errmsg"));
            }
        }
        catch (Exception e)
        {
            isSuccess = false;
            e.printStackTrace();
            logger.error("更新微信token异常");
        }
    }
}
